
package logic.actions.queryAll;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import logic.actions.SEISaudeAction;
import logic.beans.DBElementIF;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import controller.SEISaudeDefaultFacade;

public class QueryAllElementsAction<E extends DBElementIF> extends SEISaudeAction {
	@SuppressWarnings("unchecked")
	@Override
	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) throws Exception {
		ActionMessages errors = getErrors(request);
		ActionMessages messages = getMessages(request);
		
		if (isUserChecked() && !checkUserLogged(request)) {
			messages.add("store success",new ActionMessage("login.error.userName.mustLogin"));
			saveMessages(request,messages);
			
			return mapping.findForward("login");
		}
		
		Class<E> elementClass = (Class<E>)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
		SEISaudeDefaultFacade<E,Long> facade = SEISaudeDefaultFacade.getInstance(elementClass);
		
		try {
			List<E> elementList = facade.getAllElements();
			request.setAttribute("elementList",elementList);
		} catch (Exception ex) {
			facade.clearCurrentSession();
			errors.add("query all error",new ActionMessage("element.queryAll.error",ex.getMessage()));
		}
		
		saveErrors(request,errors);
		setUpRequest(facade,form,request);
		
		return mapping.findForward("ok");
	}
}
